package com.cheems.interceptor;

import com.cheems.exception.UserNotLoginException;
import com.cheems.utils.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * jwt令牌拦截器
 */
@Component
@Slf4j
public class JwtTokenAdminInterceptor implements HandlerInterceptor {
    @Override//运行前拦截
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        //获取请求url
        String url = request.getRequestURI();
        log.info("请求url,{}",url);

        //如果有login放行
        if (url.contains("login")||url.contains("enroll")){
            log.info("login放行");
            return true;
        }

        //获取请求头中的token
        String jwt = request.getHeader("Authorization");
        String head = request.getHeader("referer");
        //检验令牌是否存在
        if(!StringUtils.hasLength(jwt)){
            log.info("请求头中token为空");
            //抛出错误信息
            throw new UserNotLoginException("用户未登录");
        }

        //校验token令牌
        try {
            JwtUtil.parseJWT("cheems",jwt);
        } catch (Exception ex){
            response.setStatus(401);
            return false;
        }

        //放行
        log.info("校验通过放行");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}